package com.jiuyin.dianjing.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.util.DisplayUtil;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;

public class HeadPhotoAdapter extends RecyclerView.Adapter<HeadPhotoAdapter.ViewHolder> {
    ArrayList<String> mHeadList = new ArrayList<>();
    Context mContext;
    float mPhotoSize;

    public HeadPhotoAdapter(float photoSizeDP) {
        this.mPhotoSize = photoSizeDP;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View root = LayoutInflater.from(mContext).inflate(R.layout.item_head, parent, false);
        return new ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Glide.with(mContext)
                .load(mHeadList.get(position))
                .placeholder(R.mipmap.bga_pp_ic_holder_dark)
                .override(DisplayUtil.dp2px(mContext, mPhotoSize))
                .into(holder.ivHead);
        holder.ivHead.setOnClickListener(v -> {
            photoPreviewWrapper(position);
        });
    }

    /**
     * 图片预览
     */
    private void photoPreviewWrapper(int currentItemPosition) {
        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
                new BGAPhotoPreviewActivity.IntentBuilder(mContext);
        if (mHeadList.size() == 1) {
            // 预览单张图片
            photoPreviewIntentBuilder.previewPhoto(mHeadList.get(currentItemPosition));
        } else if (mHeadList.size() > 1) {
            // 预览多张图片
            photoPreviewIntentBuilder.previewPhotos(mHeadList)
                    .currentPosition(currentItemPosition); // 当前预览图片的索引
        }
        mContext.startActivity(photoPreviewIntentBuilder.build());
    }

    @Override
    public int getItemCount() {
        return mHeadList.size();
    }

    public void setData(List<String> headList) {
        mHeadList.clear();
        mHeadList.addAll(headList);
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivHead;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivHead = itemView.findViewById(R.id.iv_head);
            ViewGroup.LayoutParams params = ivHead.getLayoutParams();
            params.height = DisplayUtil.dp2px(mContext, mPhotoSize);
            params.width = params.height;
            ivHead.setLayoutParams(params);
        }
    }
}
